package com.campusexpresspickup.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campusexpresspickup.entity.LogisticsOrder;
import com.campusexpresspickup.exception.Asserts;
import com.campusexpresspickup.exception.logisticsException;
import com.campusexpresspickup.page.LogisticsOrderPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.campusexpresspickup.common.RestResponse;
import com.campusexpresspickup.dto.LogisticsOrderParam;
import com.campusexpresspickup.entity.LogisticsCourier;
import com.campusexpresspickup.service.ILogisticsCourierService;
import com.campusexpresspickup.service.ILogisticsOrderService;
import java.util.Date;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/logistics-order")
public class LogisticsOrderController {

  private final ILogisticsOrderService logisticsOrderService;
  private final ILogisticsCourierService logisticsCourierService;

  public LogisticsOrderController(
      ILogisticsOrderService logisticsOrderService,
      ILogisticsCourierService logisticsCourierService) {
    this.logisticsOrderService = logisticsOrderService;
    this.logisticsCourierService = logisticsCourierService;
  }

  @Transactional
  @PostMapping(value = "/create", name = "创建任务")
  public Object createOrder(@RequestBody LogisticsOrderParam logisticsOrderParam) {
    if (!StringUtils.hasText(StringUtils.trimAllWhitespace(logisticsOrderParam.getFloor()))) {
      Asserts.error("楼号不能为空");
    }
    if (!StringUtils.hasText(StringUtils.trimAllWhitespace(logisticsOrderParam.getRoomNo()))) {
      Asserts.error("房间号不能为空");
    }
    if (!StringUtils
        .hasText(StringUtils.trimAllWhitespace(logisticsOrderParam.getCourierCompany()))) {
      Asserts.error("快递公司不能为空");
    }
    if (!StringUtils.hasText(StringUtils.trimAllWhitespace(logisticsOrderParam.getTaskName()))) {
      Asserts.error("任务名称不能为空");
    }
    if (!StringUtils.hasText(
        StringUtils.trimAllWhitespace(String.valueOf(logisticsOrderParam.getPickupCode())))) {
      Asserts.error("取件码不能为空");
    }
    if (!StringUtils.hasText(
        StringUtils.trimAllWhitespace(String.valueOf(logisticsOrderParam.getUserId())))) {
      Asserts.error("发布用户ID不能为空");
    }
    if (!StringUtils.hasText(StringUtils.trimAllWhitespace(logisticsOrderParam.getPhone()))) {
      Asserts.error("手机号码不能为空");
    }
    int count;
    LogisticsOrder logisticsOrder = new LogisticsOrder();
    logisticsOrder.setTaskName(logisticsOrderParam.getTaskName());
    logisticsOrder.setUserId(logisticsOrderParam.getUserId());
    logisticsOrder.setFloor(logisticsOrderParam.getFloor());
    logisticsOrder.setRoomNo(logisticsOrderParam.getRoomNo());
    logisticsOrder.setCourierCompany(logisticsOrderParam.getCourierCompany());
    logisticsOrder.setPickupCode(logisticsOrderParam.getPickupCode());
    logisticsOrder.setPhone(logisticsOrderParam.getPhone());
    logisticsOrder.setCreateTime(new Date());
    if (logisticsOrder.getId() != null) {
      logisticsOrder.setStatus(logisticsOrderParam.getStatus());
      count = logisticsOrderService.getBaseMapper().updateById(logisticsOrder);
    } else {
      logisticsOrder.setStatus(0);
      count = logisticsOrderService.getBaseMapper().insert(logisticsOrder);
    }

    if (count > 0) {
      return RestResponse.ok(logisticsOrder.getId(), "创建成功");
    }

    return RestResponse.error("创建失败");
  }

  @GetMapping(value = "/{id}", name = "订单详情")
  public Object getOrderById(@PathVariable Long id) {
    LogisticsOrder logisticsOrder = logisticsOrderService.getBaseMapper().selectById(id);
    if (logisticsOrder == null) {
      Asserts.error("订单不存在");
    }
    return RestResponse.ok(logisticsOrder, "查询成功");
  }

  @Transactional
  @GetMapping(value = "/updateStatus/{id}", name = "修改订单状态")
  public Object updateOrderStatusById(@PathVariable Integer id, @RequestParam("status")
      Integer status, @RequestParam("courierId") Integer courierId) {
    LogisticsOrder logisticsOrder = new LogisticsOrder();
    logisticsOrder.setId(id);
    logisticsOrder.setStatus(status);
    logisticsOrder.setCourierId(courierId);
    LogisticsCourier logisticsCourier = new LogisticsCourier();
    logisticsCourier.setCourierId(courierId);
    LogisticsCourier courier = logisticsCourierService.getBaseMapper()
        .selectOne(new QueryWrapper<>(logisticsCourier));
    if (courier == null) {
      throw new logisticsException("该快递员ID不存在");
    }

    int count = 10;
    if (status == 1) {
      logisticsOrder.setStartTime(new Date());
    } else if (status == 2) {
      int orderCount = courier.getOrderCount() == null ? 0 : courier.getOrderCount();
      logisticsCourierService
          .updateOrderCountById(courier.getId(), orderCount + count, id);
      logisticsOrder.setStatus(status);
      logisticsOrder.setFinishTime(new Date());
    } else if (status == 3) {
      logisticsOrder.setDeliveryTime(new Date());
    }
    int updateCount = logisticsOrderService.getBaseMapper().updateById(logisticsOrder);
    if (updateCount > 0) {
      return RestResponse.ok("修改成功");
    }
    return RestResponse.error("修改失败");
  }

  @PostMapping(value = "/list", name = "列表")
  public Object getOrderList(@RequestBody LogisticsOrderPage logisticsOrderPage) {
    PageHelper.startPage(logisticsOrderPage.getPageStart(), logisticsOrderPage.getPageSize());
    List<LogisticsOrder> orderListByPage = logisticsOrderService
        .getOrderListByPage(logisticsOrderPage);
    return RestResponse.ok(new PageInfo<>(orderListByPage), "查询成功");
  }

  @GetMapping(value = "/delete/{id}", name = "删除")
  public Object deleteOrderById(@PathVariable Long id) {
    int delete = logisticsOrderService.getBaseMapper().deleteById(id);
    if (delete > 0) {
      return RestResponse.ok("删除成功");
    }
    return RestResponse.error("删除失败");
  }
}
